package proxy

import (
	"net/http"

	mysqlproxy "gitee.com/xuender/mysql-proxy"
	"gitee.com/xuender/mysql-proxy/pb"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/xuender/oils/base"
	"github.com/xuender/oils/cryptos"
	"github.com/xuender/oils/logs"
)

type AuthService struct {
	c *pb.Config
}

func NewAuthService(config *pb.Config) *AuthService {
	return &AuthService{
		c: config,
	}
}

func (p *AuthService) Group(group *gin.RouterGroup) {
	group.GET("", p.Hander, p.Get)
	group.POST("", p.Post)
	group.DELETE("", p.Delete)
}

func (p *AuthService) Get(ctx *gin.Context) {
	user := ctx.GetString(gin.AuthUserKey)
	logs.Debugw("get", gin.AuthUserKey, user)
	ctx.JSON(http.StatusOK, user)
}

func (p *AuthService) Delete(ctx *gin.Context) {
	session := sessions.Default(ctx)
	session.Delete(gin.AuthUserKey)
	base.Panic(session.Save())
	ctx.JSON(http.StatusOK, true)
}

func (p *AuthService) Post(ctx *gin.Context) {
	user := &pb.User{}
	base.Panic(ctx.Bind(user))

	if password, has := p.c.Auth[user.User]; has {

		if cryptos.IsEncrypt(password) {
			password = base.Panic1(cryptos.Decrypt(password, mysqlproxy.DefaultKey))
		}

		if password == user.Password {
			session := sessions.Default(ctx)
			session.Set(gin.AuthUserKey, user.User)
			base.Panic(session.Save())
			logs.Infow("auth", gin.AuthUserKey, user.User)
			ctx.JSON(http.StatusOK, user.User)

			return
		}
	}

	logs.Warnw("post", "user", user.User, "password", user.Password)
	ctx.JSON(http.StatusUnauthorized, ErrPassword)
}

func (p *AuthService) Hander(ctx *gin.Context) {
	session := sessions.Default(ctx)
	user := session.Get(gin.AuthUserKey)
	logs.Debugw("authHander", gin.AuthUserKey, user)

	if user == nil || user == "" {
		ctx.AbortWithStatus(http.StatusUnauthorized)

		return
	}

	ctx.Set(gin.AuthUserKey, user)
}
